import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { 
  NavBar, 
  Button, 
  Form, 
  Input, 
  TextArea, 
  ImageUploader, 
  Toast,
  Radio,
  Space
} from 'antd-mobile';
import type { ImageUploadItem } from 'antd-mobile/es/components/image-uploader';
import './Com/Complaince.css';

const Complaince: React.FC = () => {
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const [fileList, setFileList] = useState<ImageUploadItem[]>([]);
  const [complaintType, setComplaintType] = useState<string>('');
  const [loading, setLoading] = useState(false);

  const handleBack = () => {
    navigate('/app/my');
  };

  const complaintTypes = [
    { label: '商品质量问题', value: 'quality' },
    { label: '配送服务问题', value: 'delivery' },
    { label: '客服态度问题', value: 'service' },
    { label: '团长服务问题', value: 'leader' },
    { label: '价格争议', value: 'price' },
    { label: '退换货问题', value: 'return' },
    { label: '平台技术问题', value: 'technical' },
    { label: '其他问题', value: 'other' }
  ];

  interface FormValues {
    description: string;
    contact: string;
  }

  const handleSubmit = async (values: FormValues) => {
    if (!complaintType) {
      Toast.show('请选择投诉类型');
      return;
    }
    
    if (!values.description) {
      Toast.show('请详细描述问题');
      return;
    }

    setLoading(true);
    
    try {
      // 模拟提交投诉
      const complaintData = {
        type: complaintType,
        description: values.description,
        contact: values.contact,
        images: fileList.map(item => item.url),
        submitTime: new Date().toISOString()
      };
      
      console.log('提交投诉:', complaintData);
      
      // 模拟网络请求
      await new Promise(resolve => setTimeout(resolve, 1500));
      
      Toast.show({
        icon: 'success',
        content: '投诉提交成功，我们会尽快处理',
        duration: 2000
      });
      
      // 清空表单
      form.resetFields();
      setFileList([]);
      setComplaintType('');
      
      // 延迟返回上一页
      setTimeout(() => {
        navigate('/app/my');
      }, 2000);
      
    } catch {
      Toast.show({
        icon: 'fail',
        content: '提交失败，请重试'
      });
    } finally {
      setLoading(false);
    }
  };

  const uploadImage = async (file: File) => {
    // 模拟图片上传
    return new Promise<ImageUploadItem>((resolve) => {
      const reader = new FileReader();
      reader.onload = (e) => {
        resolve({
          url: e.target?.result as string,
          thumbnailUrl: e.target?.result as string,
          key: Date.now().toString()
        });
      };
      reader.readAsDataURL(file);
    });
  };



  return (
    <div className="complaince-container">
      <NavBar onBack={handleBack} back="返回">
        投诉建议
      </NavBar>
      
      <div className="complaince-content">
        <div className="complaince-header">
          <h3>我要投诉</h3>
          <p>请详细描述您遇到的问题，我们会认真处理每一个投诉</p>
        </div>
        
        <Form
          form={form}
          onFinish={handleSubmit}
          layout="vertical"
          className="complaince-form"
        >
          <div className="form-section">
            <div className="section-title">投诉类型</div>
            <Radio.Group
              value={complaintType}
              onChange={(val) => setComplaintType(val as string)}
            >
              <Space direction="vertical" style={{ width: '100%' }}>
                {complaintTypes.map(type => (
                  <Radio 
                    key={type.value} 
                    value={type.value}
                    style={{ 
                      width: '100%', 
                      padding: '12px 0',
                      borderBottom: '1px solid #f0f0f0'
                    }}
                  >
                    {type.label}
                  </Radio>
                ))}
              </Space>
            </Radio.Group>
          </div>

          <div className="form-section">
            <div className="section-title">详细描述 *</div>
            <Form.Item
              name="description"
              rules={[
                { required: true, message: '请详细描述问题' },
                { min: 10, message: '描述至少10个字符' }
              ]}
            >
              <TextArea
                placeholder="请详细描述您遇到的问题，包括时间、地点、具体情况等信息"
                rows={6}
                maxLength={500}
                showCount
              />
            </Form.Item>
          </div>

          <div className="form-section">
            <div className="section-title">上传图片</div>
            <div className="upload-tip">
              最多上传3张图片，每张不超过5MB
            </div>
            <ImageUploader
              value={fileList}
              onChange={setFileList}
              upload={uploadImage}
              maxCount={3}
              multiple
              accept="image/*"
            />
          </div>

          <div className="form-section">
            <div className="section-title">联系方式</div>
            <Form.Item
              name="contact"
              rules={[
                { required: true, message: '请输入联系方式' },
                { 
                  pattern: /^1[3-9]\d{9}$/, 
                  message: '请输入正确的手机号码' 
                }
              ]}
            >
              <Input
                placeholder="请输入您的手机号码"
                type="tel"
                clearable
              />
            </Form.Item>
          </div>

          <div className="form-section">
            <div className="tips">
              <div className="tips-title">温馨提示：</div>
              <ul>
                <li>请如实填写投诉内容，我们会在24小时内处理</li>
                <li>恶意投诉将被记录，影响您的信用记录</li>
                <li>如需紧急处理，请联系客服热线：400-123-4567</li>
                <li>处理结果将通过短信或站内消息通知您</li>
              </ul>
            </div>
          </div>

          <div className="submit-section">
            <Button 
              type="submit" 
              color="primary" 
              size="large" 
              loading={loading}
              disabled={loading}
              block
            >
              {loading ? '提交中...' : '提交投诉'}
            </Button>
          </div>
        </Form>
      </div>
    </div>
  );
};

export default Complaince;